package com.asset.salesforce.validator;

import java.util.List;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.springframework.beans.factory.annotation.Autowired;

import com.asset.salesforce.domain.StockSku;
import com.asset.salesforce.form.StockCategoryForm;
import com.asset.salesforce.form.StockSkuForm;
import com.asset.salesforce.service.InventoryService;

public class QuantityCheckerContraintValidator implements ConstraintValidator<QuantityChecker, Object>{

	@Autowired
	private InventoryService inventoryService;
	@Override
	public void initialize(QuantityChecker arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
		StockSkuForm stockSkuForm = (StockSkuForm)object;
		List<StockSku> stockSkus = inventoryService.getAllSKUsByEmpId(stockSkuForm.getEmpId(),stockSkuForm.getParentId());
		Integer totalQuantity = 0;
		for (StockSku stockSku : stockSkus) {
			String quantity = stockSku.getQuantity();
			Integer quantityCoverted = Integer.parseInt(quantity);
			totalQuantity = totalQuantity+quantityCoverted;
		}
		String quantity= stockSkuForm.getQuantity();
		if(!quantity.equals("")){
			if(quantity.matches("[0-9]*$")){
		Integer sum = totalQuantity+Integer.parseInt(quantity);
		String ProductQuantity = inventoryService.getProductsById(stockSkuForm.getParentId()).getQuantity();
		if(Integer.parseInt(ProductQuantity)>= sum){
			return true;
		}
		else{
		return false;
		}
		}
			else{
				constraintValidatorContext.buildConstraintViolationWithTemplate("Please Enter the quantity in number").addNode("quantity").addConstraintViolation();
				constraintValidatorContext.disableDefaultConstraintViolation();
				return false;
			}
	}
		else{
			constraintValidatorContext.buildConstraintViolationWithTemplate("You Must Enter the quantity").addNode("quantity").addConstraintViolation();
			constraintValidatorContext.disableDefaultConstraintViolation();
			return false;
		}
	}

}
